package com.icesoft.base.manager.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icesoft.core.common.exception.CheckException;
import com.icesoft.core.common.exception.CheckNoLogException;
import com.icesoft.core.web.helper.excel.ExcelUtil;

/**
 * @author XHH
 */
public abstract class BaseImportAction<T> {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());

	/***
	 * 将map转成实体bean，key：表头，value：实体数据
	 * 
	 * @throws CheckNoLogException
	 *             不停止执行，合法的数据执行导入
	 * @throws IllegalArgumentException
	 *             停止执行导入，所有数据都不导入
	 */
	protected abstract T convert(Map<String, String> model);

	protected void afterRead(Collection<Map<String, String>> varList) {
		if (log.isTraceEnabled()) {
			log.trace("读到的excel数据：{}", varList);
		}
	}

	public String errorTitle() {
		return "错误信息";
	}

	public final List<T> readExcel(String filepath, List<Map<String, String>> failures) {
		List<T> models = new ArrayList<>();
		Collection<Map<String, String>> varList;
		try {
			varList = ExcelUtil.readFromExcel(filepath);
		} catch (IOException e) {
			log.error("IOException，读取excel失败", e);
			throw new CheckException("读取excel失败：" + e.getMessage());
		}
		afterRead(varList);
		varList.stream().forEach(map -> {
			try {
				T model = convert(map);
				if (model != null) {
					log.debug("读到数据转换成功：{}", map);
					models.add(model);
				}
			} catch (CheckException | CheckNoLogException e) {
				map.put(errorTitle(), e.getMessage());
				log.debug("读到数据校验失败，{}：{}", e.getMessage(), map);
				failures.add(map);
			}

		});
		return models;
	}

}
